package com.blogspot.oguzhan.game;


public abstract class Game {

	private Player[] players;
	private int playerLimit;
	private int numberOfPlayers;

	public Game(int maximumNumberOfPlayers) {
		this.playerLimit = maximumNumberOfPlayers;
		this.numberOfPlayers = 0;
		this.players = new Player[maximumNumberOfPlayers];
	}
	
	public final void join(Player newPlayer) {
		if (playerLimit == numberOfPlayers) 
			throw new MaximumNumberOfPlayersReachedException();
		
		for (Player player : players) 
			if (newPlayer.equals(player)) 
				throw new DuplicateRegistrationIsNotAllowedException();
		
		players[numberOfPlayers++] = newPlayer;
	}

	public final void leave(Player player) {
		for (int i = 0; i < numberOfPlayers; i++) 
			if(player.equals(players[i])) {
				players[i] = null;
				numberOfPlayers--;
				return;
			}
		
		throw new PlayerNotJoinedGameException();
	}

	public final int getNumberOfPlayers() {
		return numberOfPlayers;
	}
	
	public final Player getPlayer(int index) {
		if(index-1 < numberOfPlayers)
			return players[index-1];
		else
			throw new PlayerNotExistException();
	}
	
	public final boolean isPlayerJoined(Player player) {
		for (int i = 0; i < numberOfPlayers; i++) 
			if (player.equals(players[i])) 
				return true;

		return false;
	}

	public final void checkPlayer(Player player) {
		if (!isPlayerJoined(player)) 
			throw new PlayerNotExistException();
	}
	
	public static class MaximumNumberOfPlayersReachedException extends RuntimeException {
		private static final long serialVersionUID = 1L;
	}
	
	public static class DuplicateRegistrationIsNotAllowedException extends RuntimeException {
		private static final long serialVersionUID = 1L;
	}

	public static class PlayerNotJoinedGameException extends RuntimeException {
		private static final long serialVersionUID = 1L;
	}

	public static class PlayerNotExistException extends RuntimeException {
		private static final long serialVersionUID = 1L;
	}
}